// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space
// Source File Name:   AuthTokenServletbak.java

package weaver.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.util.SessionUtil;
import weaver.interfaces.email.SSLClient;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class AuthTokenServlet extends HttpServlet
{

    private static Log newlog = LogFactory.getLog(AuthTokenServlet.class);
    private ServletContext application;

    public AuthTokenServlet()
    {
    }

    public void init(ServletConfig servletconfig)
            throws ServletException
    {
        application = servletconfig.getServletContext();
    }

    protected void doPost(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)
            throws ServletException, IOException
    {
        //super.doGet(httpservletrequest, httpservletresponse);
        this.doGet(httpservletrequest, httpservletresponse);
    }

    protected void doGet(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse,JSONObject jsonObject)
            throws ServletException, IOException
    {
        newlog.info("进入单点测试"+jsonObject);
        String s = Util.null2String(httpservletrequest.getParameter("code"));
        String s1 = Util.null2String(httpservletrequest.getParameter("state"));
        String s2 = Util.null2String(Prop.getPropValue("authlogin", "tokenurl"));
        String s3 = Util.null2String(Prop.getPropValue("authlogin", "userinfourl"));
        String s4 = Util.null2String(Prop.getPropValue("authlogin", "client_secret"));
        String s5 = Util.null2String(Prop.getPropValue("authlogin", "grant_type"));
        String s6 = Util.null2String(Prop.getPropValue("authlogin", "client_id"));
        LinkedHashMap linkedhashmap = new LinkedHashMap();
        linkedhashmap.put("client_id", s6);
        linkedhashmap.put("grant_type", s5);
        linkedhashmap.put("code", s);
        linkedhashmap.put("client_secret", s4);
        newlog.info("=============doPost "+s2+" start...");
//		JSONObject jsonobject = doPost(s2, linkedhashmap);
        newlog.info("=============doPost "+s2+" end...");
//		newlog.info((new StringBuilder()).append("get tokenresult :").append(jsonobject).toString());
//		if (jsonobject == null)
//		{
//			newlog.info((new StringBuilder()).append("获取Token失败，错误信息 :").append(s2).append("接口返回为空").toString());
//			httpservletresponse.sendRedirect((new StringBuilder()).append("/login/SingleLoginerror.jsp?args=2&msg=").append(s2).append("接口返回为空").toString());
//			return;
//		}
//		if (jsonobject.containsKey("errorcode"))
//		{
//			newlog.info((new StringBuilder()).append("获取Token失败，错误信息 :").append(jsonobject.getString("msg")).toString());
//			httpservletresponse.sendRedirect((new StringBuilder()).append("/login/SingleLoginerror.jsp?args=2&msg=").append(jsonobject.getString("msg")).toString());
//			return;
//		}
//		String s7 = jsonobject.getString("access_token");
//		s3 = (new StringBuilder()).append(s3).append("?access_token=").append(s7).append("&client_id=").append(s6).toString();
        newlog.info("=============doGet "+s3+" start...");
//		JSONObject jsonobject1 = doGet(s3);
        newlog.info("=============doGet "+s3+" end...");
//		if (jsonobject1 == null)
//		{
//			newlog.info((new StringBuilder()).append("获取用户信息失败，错误信息 :").append(s3).append("接口返回为空").toString());
//			httpservletresponse.sendRedirect((new StringBuilder()).append("/login/SingleLoginerror.jsp?args=2&msg=").append(s3).append("接口返回为空").toString());
//			return;
//		}
//		if (jsonobject1.containsKey("errorcode"))
//		{
//			newlog.info((new StringBuilder()).append("获取用户信息失败，错误信息 :").append(jsonobject1.getString("msg")).toString());
//			httpservletresponse.sendRedirect((new StringBuilder()).append("/login/SingleLoginerror.jsp?args=2&msg=").append(jsonobject1.getString("msg")).toString());
//			return;
//		} else
//		{
        String s8 = httpservletrequest.getParameter("loginid");
        newlog.info("=============createUserSessionAndGetDispatcherUrl "+s8+" start...");
        String s9 = createUserSessionAndGetDispatcherUrl(httpservletrequest, httpservletresponse, s8);
        newlog.info("=============createUserSessionAndGetDispatcherUrl "+s8+" end...");
        httpservletresponse.sendRedirect(s9);
        return;
//		}
    }

    /**
     * 构造用户session并获取转发地址
     * @param username 用户名
     * @return 跳转地址
     */
    private String createUserSessionAndGetDispatcherUrl(HttpServletRequest request, HttpServletResponse response, String username){
        RecordSet rs = new RecordSet();

        //查询OA中是否有username的人员
        if(!"".equals(username)){
            String sql = "select * from HrmResource where loginid='"+username+"' and status<4";
            newlog.error("当前用户信息=="+sql);
            rs.execute(sql);

            User user_new = null;
            if(rs.next()){
                String uid = rs.getString("id");
                //OA有相关人员
                User user = (User)request.getSession(true).getAttribute("weaver_user@bean");
                if(user==null){
                    newlog.error("用户session还未构造，新登录");
                }else if((user!=null && !user.getLoginid().equals(username))){
                    newlog.error("老用户session="+user.getLoginid()+" 新用户session="+username);
                }

                if(user==null || (user!=null && !user.getLoginid().equals(username))){
                    // 人员还未登录，构造人员
                    SessionUtil.createSession(uid, request, response);
                }else{
                    // 人员已登录
                    user_new = user;
                }



                // 用户的登录后的页面
                String tourl = "/wui/index.html#/main";
                /*weaver.systeminfo.template.UserTemplate ut = new weaver.systeminfo.template.UserTemplate();
                ut.getTemplateByUID(user_new.getUID(), user_new.getUserSubCompany1());
                int templateId = ut.getTemplateId();
                int extendTempletid = ut.getExtendtempletid();
                int extendtempletvalueid = ut.getExtendtempletvalueid();
                String defaultHp = ut.getDefaultHp();
                request.getSession(true).setAttribute("defaultHp", defaultHp);


                if(extendTempletid != 0) {
                    rs.executeSql("select id,extendname,extendurl from extendHomepage  where id = " + extendTempletid);
                    if(rs.next()) {
                        int id = Util.getIntValue(rs.getString("id"));
                        String extendurl = Util.null2String(rs.getString("extendurl"));
                        rs.executeSql("select * from extendHpWebCustom where templateid = " + templateId);
                        String defaultshow = "";
                        if(rs.next()) {
                            defaultshow = Util.null2String(rs.getString("defaultshow"));
                        }
                        String param = "";
                        if(!defaultshow.equals("")) {
                            param = "&" + defaultshow.substring(defaultshow.indexOf("?")+1);
                        }
                        String gopage = Util.null2String(request.getParameter("gopage"));
                        if(gopage.length() > 0) {
                            tourl = "/login/RemindLogin.jsp?RedirectFile="+extendurl+"/index.jsp?templateId="+templateId+param+"&gopage="+gopage;
                        } else {
                            tourl = "/login/RemindLogin.jsp?RedirectFile="+extendurl+"/index.jsp?templateId="+templateId+param;
                        }
                    }
                } else {
                    tourl = "/wui/main-cs.jsp.bak";
                }*/

                //tourl = SessionUtil.getHomePageAfterLogin(request, response);

                return tourl;
            }else{
                //OA中查无此人，必须重新登录
                newlog.error("OA中查无此人，必须重新登录");
                return "/login/SingleLoginerror.jsp?args=4";
            }
        }else{
            newlog.error("传入的username为空");
            return "/login/SingleLoginerror.jsp?args=4";
        }
    }

    private String getLogMessage(String s)
    {
        String s1 = "";
        RecordSet recordset = new RecordSet();
        String s2 = "";
        if (recordset.getDBType().equals("oracle"))
            s2 = (new StringBuilder()).append("select * from (select * from SysMaintenanceLog where relatedid = ").append(s).append(" and operatetype='6' and operateitem='60' order by id desc ) where rownum=1 ").toString();
        else
        if (recordset.getDBType().equals("db2"))
            s2 = (new StringBuilder()).append("select * from SysMaintenanceLog where relatedid = ").append(s).append(" and operatetype='6' and operateitem='60' order by id desc fetch first 1 rows only ").toString();
        else
        if (recordset.getDBType().equals("mysql"))
            s2 = (new StringBuilder()).append("SELECT t2.* FROM (SELECT * FROM SysMaintenanceLog WHERE relatedid = ").append(s).append(" and  operatetype='6' AND operateitem='60' ORDER BY id DESC) t2  LIMIT 1 ,1").toString();
        else
            s2 = (new StringBuilder()).append("select top 1 * from SysMaintenanceLog where relatedid = ").append(s).append(" and operatetype='6' and operateitem='60' order by id desc").toString();
        recordset.executeSql(s2);
        if (recordset.next())
            s1 = (new StringBuilder()).append(recordset.getString("clientaddress")).append(" ").append(recordset.getString("operatedate")).append(" ").append(recordset.getString("operatetime")).toString();
        return s1;
    }

    private String getisIE(HttpServletRequest httpservletrequest)
    {
        String s = "true";
        String s1 = httpservletrequest.getHeader("User-Agent").toLowerCase();
        if (s1.indexOf("rv:11") == -1 && s1.indexOf("msie") == -1)
            s = "false";
        if (s1.indexOf("rv:11") > -1 || s1.indexOf("msie") > -1)
            s = "true";
        return s;
    }

    private JSONObject doPost(String s, Map map)
    {
        String s1 = "";
        JSONObject jsonobject = null;
        try
        {
            SSLClient sslclient = null;
            sslclient = new SSLClient();
            HttpPost httppost = new HttpPost(s);
            httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            ArrayList arraylist = new ArrayList();
            String s2;
            for (Iterator iterator = map.keySet().iterator(); iterator.hasNext(); arraylist.add(new BasicNameValuePair(s2, (String)map.get(s2))))
                s2 = (String)iterator.next();

            UrlEncodedFormEntity urlencodedformentity = new UrlEncodedFormEntity(arraylist, "UTF-8");
            httppost.setEntity(urlencodedformentity);
            org.apache.http.client.methods.CloseableHttpResponse closeablehttpresponse = sslclient.execute(httppost);
            HttpEntity httpentity = closeablehttpresponse.getEntity();
            if (httpentity != null)
                s1 = EntityUtils.toString(httpentity, "UTF-8");
            jsonobject = JSON.parseObject(s1);
        }
        catch (Exception exception)
        {
            newlog.error((new StringBuilder()).append("访问").append(s).append("失败！").toString(), exception);
        }
        return jsonobject;
    }

    private JSONObject doGet(String s)
    {
        String s1 = "";
        JSONObject jsonobject = null;
        try
        {
            SSLClient sslclient = null;
            sslclient = new SSLClient();
            HttpGet httpget = new HttpGet(s);
            httpget.setHeader("Content-Type", "application/x-www-form-urlencoded");
            org.apache.http.client.methods.CloseableHttpResponse closeablehttpresponse = sslclient.execute(httpget);
            HttpEntity httpentity = closeablehttpresponse.getEntity();
            if (httpentity != null)
                s1 = EntityUtils.toString(httpentity, "UTF-8");
            jsonobject = JSON.parseObject(s1);
        }
        catch (Exception exception)
        {
            newlog.error((new StringBuilder()).append("访问").append(s).append("失败！").toString(), exception);
        }
        return jsonobject;
    }

}
